package cn.yl.comment.server.service.impl;

import cn.yl.api.server.util.JwtUtil;
import cn.yl.comment.server.entity.CourseComment;
import cn.yl.comment.server.entity.CourseCommentFavoriteRecord;
import cn.yl.comment.server.entity.dto.CourseCommentDto;
import cn.yl.comment.server.entity.vo.CourseCommentVo;
import cn.yl.comment.server.mapper.CourseCommentMapper;
import cn.yl.comment.server.service.CourseCommentFavoriteRecordService;
import cn.yl.comment.server.service.CourseCommentService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程留言表 服务实现类
 * </p>
 *
 * @author yl
 * @since 2022-04-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CourseCommentServiceImpl extends ServiceImpl<CourseCommentMapper, CourseComment> implements CourseCommentService {

    @Autowired
    private CourseCommentFavoriteRecordService courseCommentFavoriteRecordService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public List<CourseCommentDto> getCourseCommentList(Integer courseId, Integer current, Integer size) {
        Page<CourseComment> page = new Page<>(current, size);
        QueryWrapper<CourseComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
//        wrapper.orderByDesc("like_count");
        this.page(page, wrapper);
        List<CourseComment> list = page.getRecords();
        ArrayList<CourseCommentDto> courseCommentDtoList = new ArrayList<>();
        list.forEach(courseComment -> {
            CourseCommentDto commentDto = new CourseCommentDto();
            BeanUtils.copyProperties(courseComment, commentDto);
            commentDto.setUserId(null);
            QueryWrapper<CourseCommentFavoriteRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("comment_id", courseComment.getId()).eq("is_del", 0);
            List<CourseCommentFavoriteRecord> recordList = courseCommentFavoriteRecordService.list(queryWrapper);
            courseCommentDtoList.add(commentDto.setFavoriteRecords(recordList));
        });
        return courseCommentDtoList;
    }

    @Override
    public boolean saveCourseComment(CourseCommentVo courseCommentVo, String jwt) {
        Claims claims = jwtUtil.parseJWT(jwt);
        int userId = Integer.parseInt(claims.getId());
//        String subject = claims.getSubject();
//        UserDto userDto = JSON.parseObject(subject, UserDto.class);
        CourseComment courseComment = new CourseComment();
        BeanUtils.copyProperties(courseCommentVo, courseComment);
        courseComment.setUserId(userId).setSectionId(0).setLessonId(0).setLastOperator(userId);
        return this.save(courseComment);
    }

    @Override
    public synchronized boolean saveFavorite(Integer commentId, String jwt) {
        boolean flag = false;
        Claims claims = jwtUtil.parseJWT(jwt);
        int id = Integer.parseInt(claims.getId());

        QueryWrapper<CourseCommentFavoriteRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id).eq("comment_id", commentId);
        CourseCommentFavoriteRecord favoriteRecord = this.courseCommentFavoriteRecordService.getOne(wrapper);
        if (favoriteRecord == null) {
            CourseCommentFavoriteRecord courseCommentFavoriteRecord = new CourseCommentFavoriteRecord();
            courseCommentFavoriteRecord.setUserId(id).setCommentId(commentId).setDel(false);
            this.courseCommentFavoriteRecordService.save(courseCommentFavoriteRecord);
        } else {
            if (!favoriteRecord.getDel()) {
                return flag;
            }
            UpdateWrapper<CourseCommentFavoriteRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("is_del", 0).eq("user_id", id).eq("comment_id", commentId);
            flag = this.courseCommentFavoriteRecordService.update(updateWrapper);
        }
        CourseComment comment = this.getById(commentId);
        comment.setLikeCount(comment.getLikeCount() + 1);
        flag = this.updateById(comment);
        return flag;

    }

    @Override
    public synchronized boolean cancelFavorite(Integer commentId, String jwt) {
        boolean flag = false;
        Claims claims = jwtUtil.parseJWT(jwt);
        int id = Integer.parseInt(claims.getId());
        QueryWrapper<CourseCommentFavoriteRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id).eq("comment_id", commentId);
        CourseCommentFavoriteRecord favoriteRecord = this.courseCommentFavoriteRecordService.getOne(wrapper);
        CourseComment comment = this.getById(commentId);
        if (!favoriteRecord.getDel()) {
            //取消点赞
            UpdateWrapper<CourseCommentFavoriteRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("is_del", 1).eq("user_id", id).eq("comment_id", commentId);
            courseCommentFavoriteRecordService.update(updateWrapper);

            if (comment.getLikeCount() > 0) {
                comment.setLikeCount(comment.getLikeCount() - 1);
                flag = this.updateById(comment);
            }
        } else {
            //点赞
            UpdateWrapper<CourseCommentFavoriteRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("is_del", 0).eq("user_id", id).eq("comment_id", commentId);
            courseCommentFavoriteRecordService.update(updateWrapper);

            comment.setLikeCount(comment.getLikeCount() + 1);
            flag = this.updateById(comment);
        }
        return flag;
    }
}
